﻿using Game;
using GameEntitySystem;
using Engine;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TemplatesDatabase;
using System.Drawing;

namespace SCIENEW
{
	public class DiversionBlockBehavior : DeviceBehavior
	{
		public DiversionBlockBehavior(Project project) : base(project)
		{
			m_subsystemPickables = project.FindSubsystem<SubsystemPickables>(true);
			m_subsystemProjectiles = project.FindSubsystem<SubsystemProjectiles>(true);
			//m_subsystemEnginePower = project.FindSubsystem<SubsystemEnginePower>(true);
			m_subsystemTerrain = project.FindSubsystem<SubsystemTerrain>(true);
		}
		public SubsystemPickables m_subsystemPickables;
		public SubsystemProjectiles m_subsystemProjectiles;
		public SubsystemTerrain m_subsystemTerrain;

		public override void OnHitByProjectile(CellFace cellFace, WorldItem worldItem)
		{
			if (worldItem.ToRemove)
				return;
			int value = m_subsystemTerrain.Terrain.GetCellValue(cellFace.X, cellFace.Y, cellFace.Z);
			//if (Terrain.ExtractContents(value) != DiversionBlock.Index) return;
			int face = DevicesUtils.GetInnerData(m_subsystemTerrain.Terrain.GetCellValueFast(cellFace.X, cellFace.Y, cellFace.Z));
			Vector3 v = CellFace.FaceToVector3(face);
			Vector3 v2 = worldItem.Velocity;
            int count = 1;
            if (worldItem is Pickable pickable) {
                count = pickable.Count;
            }
            while (count > 0) {
                if (m_subsystemProjectiles.FireProjectile(worldItem.Value, new Vector3(cellFace.X, cellFace.Y, cellFace.Z) + new Vector3(0.5f) + 0.75f * v, v*v2.Length(), Vector3.Zero, null) == null)
                {
                    m_subsystemPickables.AddPickable(worldItem.Value, count, new Vector3(cellFace.X, cellFace.Y, cellFace.Z) + new Vector3(0.5f) + 0.75f * v, 1f * v, null);
                    break;
                }
                count--;
            }
			worldItem.ToRemove = true;
		}

		public override void OnCollide(CellFace cellFace, float velocity, ComponentBody componentBody)
		{
			int x = cellFace.X,
				y = cellFace.Y,
				z = cellFace.Z;
			if (m_subsystemTerrain.Terrain.GetCellContentsFast(x, y, z) != IceBlock.Index || componentBody.Mass < 999f || componentBody.Density > 1f)
				return;
			m_subsystemTerrain.DestroyCell(0, x, y, z, WaterBlock.Index, false, false);
		}
	}

}
